<?php
namespace app\api\home;
use app\common\controller\ApiBase;
use app\common\model\Resource;
use OSS\OssClient;
use OSS\Core\OssException;
use think\facade\Log;

if (is_file(__DIR__.'/autoload.php')) {
    require_once __DIR__.'autoload.php';
}
if (is_file(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

/**
 * 上传接口
**/
class Upload extends ApiBase
{
    public function index(): \think\response\Json
    {

        $file = $_FILES;
        if (empty($file)){
            return json(['data'=>'','msg'=>'提交方式不正确'],0);
        }
        $data = [];
        foreach ($file as $k => $value){
           $fileName = empty($value['name']) ? '' : $value['name'];
           $fileType = empty($value['type']) ? '' : $value['type'];
           $filePath = empty($value['tmp_name']) ? '' : $value['tmp_name'];
           $fileSize = empty($value['size']) ? '' : $value['size'];
           $suffix   = pathinfo($fileName,PATHINFO_EXTENSION);
           $objectName   = md5(time().$fileName).'.'.$suffix;
           $fileType = $fileType ? explode('/',$fileType)[0] : 'exampledir';
           $object   = $fileType.'/'.$objectName;
           $fileData = $this->oss_upload($filePath,$object);
//           $url     = empty($fileData['url']) ? '' : $fileData['url'];
           $success = empty($fileData['success']) ? '' : $fileData['success'];
           $data[$k]['url']       = $object;
           $data[$k]['success']   = $success;
           $data[$k]['type']   = $fileType;
           $data[$k]['size']   = $fileSize;
           (new \app\common\model\Resource)->insert([
               'name'=>$fileName,
               'type'=>$fileType,
               'size'=>round($fileSize/1024, 2),
               'suffix'=>$suffix,
               'url'=>$object,
               'success'=>$success,
               'ctime'=>date('Y-m-d H:i:s'),
           ]);
        }
        return json($data);
    }

    public function oss_upload($filePath , $object)
    {
        if (empty($filePath)) return false;
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        $accessKeyId = config("aly_config.accessKeyId");
        $accessKeySecret = config("aly_config.accessKeySecret");
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        $endpoint = config("aly_config.endpoint");
        // 填写Bucket名称，例如examplebucket。
        $bucket= config("aly_config.bucket");
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
//        $object = "exampledir/hh.jpg";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
//        $filePath = "C:\Users\Administrator\Desktop\hh.jpg";
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch(OssException $e) {
            Log::info('OSSUpdateFileException_'.$e->getMessage());
        }
        return ['url'=>config('aly_config.oss_upload_url').$object,'success'=>''];
    }
}